using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;

namespace MatrixFramework.Shared.Domain.Photos
{
    /// <summary>
    /// 人物领域实体
    /// 用于人脸识别结果中的人物管理
    /// </summary>
    public class Person : FullAuditedAggregateRoot<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 人物姓名
        /// </summary>
        [Required]
        [MaxLength(200)]
        public virtual string Name { get; protected set; }

        /// <summary>
        /// 人物昵称
        /// </summary>
        [MaxLength(100)]
        public virtual string Nickname { get; protected set; }

        /// <summary>
        /// 人物描述
        /// </summary>
        [MaxLength(1000)]
        public virtual string Description { get; protected set; }

        /// <summary>
        /// 人物类型
        /// </summary>
        public virtual PersonType PersonType { get; protected set; }

        /// <summary>
        /// 性别
        /// </summary>
        public virtual Gender? Gender { get; protected set; }

        /// <summary>
        /// 出生日期
        /// </summary>
        public virtual DateTime? BirthDate { get; protected set; }

        /// <summary>
        /// 关系类型（如家人、朋友、同事等）
        /// </summary>
        [MaxLength(100)]
        public virtual string Relationship { get; protected set; }

        /// <summary>
        /// 人物标签
        /// </summary>
        public virtual List<string> Tags { get; protected set; }

        /// <summary>
        /// 人物头像URL
        /// </summary>
        [MaxLength(500)]
        public virtual string AvatarUrl { get; protected set; }

        /// <summary>
        /// 主要照片ID（作为代表照片）
        /// </summary>
        public virtual Guid? PrimaryPhotoId { get; protected set; }

        /// <summary>
        /// 人脸特征数据（平均特征）
        /// </summary>
        public virtual byte[] AverageFaceFeatures { get; protected set; }

        /// <summary>
        /// 置信度阈值
        /// </summary>
        public virtual double ConfidenceThreshold { get; protected set; }

        /// <summary>
        /// 识别准确率
        /// </summary>
        public virtual double RecognitionAccuracy { get; protected set; }

        /// <summary>
        /// 是否为验证过的人物
        /// </summary>
        public virtual bool IsVerified { get; protected set; }

        /// <summary>
        /// 是否需要人工审核
        /// </summary>
        public virtual bool NeedsManualReview { get; protected set; }

        /// <summary>
        /// 最后识别时间
        /// </summary>
        public virtual DateTime? LastRecognitionTime { get; protected set; }

        /// <summary>
        /// 人物统计信息
        /// </summary>
        public virtual PersonStatistics Statistics { get; protected set; }

        /// <summary>
        /// 人物元数据
        /// </summary>
        public virtual Dictionary<string, object> Metadata { get; protected set; }

        /// <summary>
        /// 人物设置
        /// </summary>
        public virtual PersonSettings Settings { get; protected set; }

        /// <summary>
        /// 人脸识别记录集合
        /// </summary>
        public virtual ICollection<PhotoFace> FaceRecords { get; protected set; }

        /// <summary>
        /// 人物关系集合
        /// </summary>
        public virtual ICollection<PersonRelationship> Relationships { get; protected set; }

        /// <summary>
        /// 主要照片导航属性
        /// </summary>
        public virtual Photo PrimaryPhoto { get; protected set; }

        protected Person()
        {
            Tags = new List<string>();
            Statistics = new PersonStatistics();
            Metadata = new Dictionary<string, object>();
            Settings = new PersonSettings();
            FaceRecords = new List<PhotoFace>();
            Relationships = new List<PersonRelationship>();
        }

        public Person(
            Guid id,
            string name,
            PersonType personType = PersonType.Unknown,
            Gender? gender = null,
            Guid? tenantId = null) : base(id)
        {
            Name = name;
            PersonType = personType;
            Gender = gender;
            TenantId = tenantId;
            ConfidenceThreshold = 0.7;

            Tags = new List<string>();
            Statistics = new PersonStatistics();
            Metadata = new Dictionary<string, object>();
            Settings = new PersonSettings();
            FaceRecords = new List<PhotoFace>();
            Relationships = new List<PersonRelationship>();
        }

        /// <summary>
        /// 更新基本信息
        /// </summary>
        public virtual void UpdateBasicInfo(string name, string nickname = null, string description = null)
        {
            Name = name;
            Nickname = nickname;
            Description = description;
        }

        /// <summary>
        /// 更新人物类型
        /// </summary>
        public virtual void UpdatePersonType(PersonType personType)
        {
            PersonType = personType;
        }

        /// <summary>
        /// 更新性别
        /// </summary>
        public virtual void UpdateGender(Gender? gender)
        {
            Gender = gender;
        }

        /// <summary>
        /// 更新出生日期
        /// </summary>
        public virtual void UpdateBirthDate(DateTime? birthDate)
        {
            BirthDate = birthDate;
        }

        /// <summary>
        /// 更新关系类型
        /// </summary>
        public virtual void UpdateRelationship(string relationship)
        {
            Relationship = relationship;
        }

        /// <summary>
        /// 更新标签
        /// </summary>
        public virtual void UpdateTags(List<string> tags)
        {
            Tags = tags ?? new List<string>();
        }

        /// <summary>
        /// 添加标签
        /// </summary>
        public virtual void AddTag(string tag)
        {
            if (!string.IsNullOrWhiteSpace(tag) && !Tags.Contains(tag))
            {
                Tags.Add(tag);
            }
        }

        /// <summary>
        /// 移除标签
        /// </summary>
        public virtual void RemoveTag(string tag)
        {
            Tags.Remove(tag);
        }

        /// <summary>
        /// 设置头像URL
        /// </summary>
        public virtual void SetAvatarUrl(string avatarUrl)
        {
            AvatarUrl = avatarUrl;
        }

        /// <summary>
        /// 设置主要照片
        /// </summary>
        public virtual void SetPrimaryPhoto(Guid? primaryPhotoId)
        {
            PrimaryPhotoId = primaryPhotoId;
        }

        /// <summary>
        /// 更新人脸特征
        /// </summary>
        public virtual void UpdateFaceFeatures(byte[] averageFeatures, double accuracy)
        {
            AverageFaceFeatures = averageFeatures;
            RecognitionAccuracy = accuracy;
            LastRecognitionTime = DateTime.Now;
        }

        /// <summary>
        /// 设置置信度阈值
        /// </summary>
        public virtual void SetConfidenceThreshold(double threshold)
        {
            ConfidenceThreshold = Math.Max(0, Math.Min(1, threshold));
        }

        /// <summary>
        /// 标记为已验证
        /// </summary>
        public virtual void MarkAsVerified()
        {
            IsVerified = true;
            NeedsManualReview = false;
        }

        /// <summary>
        /// 标记为需要审核
        /// </summary>
        public virtual void MarkAsNeedsReview()
        {
            NeedsManualReview = true;
        }

        /// <summary>
        /// 更新统计信息
        /// </summary>
        public virtual void UpdateStatistics(PersonStatistics statistics)
        {
            Statistics = statistics ?? new PersonStatistics();
        }

        /// <summary>
        /// 增加照片数量
        /// </summary>
        public virtual void IncrementPhotoCount()
        {
            Statistics.TotalPhotos++;
            Statistics.LastPhotoAddedTime = DateTime.Now;
        }

        /// <summary>
        /// 减少照片数量
        /// </summary>
        public virtual void DecrementPhotoCount()
        {
            Statistics.TotalPhotos = Math.Max(0, Statistics.TotalPhotos - 1);
        }

        /// <summary>
        /// 更新元数据
        /// </summary>
        public virtual void UpdateMetadata(Dictionary<string, object> metadata)
        {
            Metadata = metadata ?? new Dictionary<string, object>();
        }

        /// <summary>
        /// 设置元数据项
        /// </summary>
        public virtual void SetMetadata(string key, object value)
        {
            Metadata[key] = value;
        }

        /// <summary>
        /// 移除元数据项
        /// </summary>
        public virtual void RemoveMetadata(string key)
        {
            Metadata.Remove(key);
        }

        /// <summary>
        /// 更新设置
        /// </summary>
        public virtual void UpdateSettings(PersonSettings settings)
        {
            Settings = settings ?? new PersonSettings();
        }

        /// <summary>
        /// 计算年龄
        /// </summary>
        public virtual int? CalculateAge()
        {
            if (!BirthDate.HasValue)
                return null;

            var today = DateTime.Today;
            var age = today.Year - BirthDate.Value.Year;
            if (BirthDate.Value.Date > today.AddYears(-age))
                age--;

            return age;
        }

        /// <summary>
        /// 检查是否为家人
        /// </summary>
        public virtual bool IsFamilyMember()
        {
            return PersonType == PersonType.Family ||
                   Tags.Contains("家人") ||
                   Tags.Contains("family");
        }

        /// <summary>
        /// 检查是否为朋友
        /// </summary>
        public virtual bool IsFriend()
        {
            return PersonType == PersonType.Friend ||
                   Tags.Contains("朋友") ||
                   Tags.Contains("friend");
        }

        /// <summary>
        /// 检查是否为同事
        /// </summary>
        public virtual bool IsColleague()
        {
            return PersonType == PersonType.Colleague ||
                   Tags.Contains("同事") ||
                   Tags.Contains("colleague");
        }

        /// <summary>
        /// 获取年龄段
        /// </summary>
        public virtual AgeGroup GetAgeGroup()
        {
            var age = CalculateAge();
            if (!age.HasValue)
                return AgeGroup.Unknown;

            return age switch
            {
                < 13 => AgeGroup.Child,
                < 20 => AgeGroup.Teenager,
                < 30 => AgeGroup.YoungAdult,
                < 50 => AgeGroup.Adult,
                < 65 => AgeGroup.MiddleAged,
                _ => AgeGroup.Senior
            };
        }
    }

    /// <summary>
    /// 人物类型枚举
    /// </summary>
    public enum PersonType
    {
        /// <summary>
        /// 未知
        /// </summary>
        Unknown = 0,

        /// <summary>
        /// 家人
        /// </summary>
        Family = 1,

        /// <summary>
        /// 朋友
        /// </summary>
        Friend = 2,

        /// <summary>
        /// 同事
        /// </summary>
        Colleague = 3,

        /// <summary>
        /// 同学
        /// </summary>
        Classmate = 4,

        /// <summary>
        /// 客户
        /// </summary>
        Client = 5,

        /// <summary>
        /// 名人
        /// </summary>
        Celebrity = 6,

        /// <summary>
        /// 公众人物
        /// </summary>
        PublicFigure = 7,

        /// <summary>
        /// 陌生人
        /// </summary>
        Stranger = 8,

        /// <summary>
        /// 自己
        /// </summary>
        Self = 9
    }

    /// <summary>
    /// 年龄段枚举
    /// </summary>
    public enum AgeGroup
    {
        /// <summary>
        /// 未知
        /// </summary>
        Unknown = 0,

        /// <summary>
        /// 儿童（0-12岁）
        /// </summary>
        Child = 1,

        /// <summary>
        /// 青少年（13-19岁）
        /// </summary>
        Teenager = 2,

        /// <summary>
        /// 青年（20-29岁）
        /// </summary>
        YoungAdult = 3,

        /// <summary>
        /// 成年人（30-49岁）
        /// </summary>
        Adult = 4,

        /// <summary>
        /// 中年（50-64岁）
        /// </summary>
        MiddleAged = 5,

        /// <summary>
        /// 老年（65岁以上）
        /// </summary>
        Senior = 6
    }

    /// <summary>
    /// 人物统计信息
    /// </summary>
    public class PersonStatistics
    {
        /// <summary>
        /// 总照片数量
        /// </summary>
        public int TotalPhotos { get; set; }

        /// <summary>
        /// 已识别照片数量
        /// </summary>
        public int RecognizedPhotos { get; set; }

        /// <summary>
        /// 高质量识别照片数量
        /// </summary>
        public int HighQualityPhotos { get; set; }

        /// <summary>
        /// 首次出现时间
        /// </summary>
        public DateTime? FirstAppearanceTime { get; set; }

        /// <summary>
        /// 最后出现时间
        /// </summary>
        public DateTime? LastAppearanceTime { get; set; }

        /// <summary>
        /// 最后添加照片时间
        /// </summary>
        public DateTime? LastPhotoAddedTime { get; set; }

        /// <summary>
        /// 按年份统计的照片数量
        /// </summary>
        public Dictionary<int, int> PhotosByYear { get; set; } = new();

        /// <summary>
        /// 按地点统计的照片数量
        /// </summary>
        public Dictionary<string, int> PhotosByLocation { get; set; } = new();

        /// <summary>
        /// 按事件统计的照片数量
        /// </summary>
        public Dictionary<string, int> PhotosByEvent { get; set; } = new();

        /// <summary>
        /// 平均出现频率（每月）
        /// </summary>
        public double AverageMonthlyFrequency { get; set; }

        /// <summary>
        /// 活跃度评分（0-100）
        /// </summary>
        public double ActivityScore { get; set; }

        /// <summary>
        /// 关系强度评分（0-100）
        /// </summary>
        public double RelationshipScore { get; set; }

        /// <summary>
        /// 认识时长（天）
        /// </summary>
        public int? KnownDays => FirstAppearanceTime.HasValue
            ? (int)(DateTime.Now - FirstAppearanceTime.Value).TotalDays
            : null;
    }

    /// <summary>
    /// 人物设置
    /// </summary>
    public class PersonSettings
    {
        /// <summary>
        /// 是否启用自动识别
        /// </summary>
        public bool EnableAutoRecognition { get; set; } = true;

        /// <summary>
        /// 是否显示在首页
        /// </summary>
        public bool ShowOnHomePage { get; set; } = false;

        /// <summary>
        /// 是否启用通知
        /// </summary>
        public bool EnableNotifications { get; set; } = true;

        /// <summary>
        /// 隐私级别
        /// </summary>
        public PrivacyLevel PrivacyLevel { get; set; } = PrivacyLevel.Normal;

        /// <summary>
        /// 是否在搜索结果中显示
        /// </summary>
        public bool ShowInSearchResults { get; set; } = true;

        /// <summary>
        /// 是否在相册中显示
        /// </summary>
        public bool ShowInGalleries { get; set; } = true;

        /// <summary>
        /// 识别敏感度
        /// </summary>
        public double RecognitionSensitivity { get; set; } = 0.7;

        /// <summary>
        /// 最小照片数量阈值
        /// </summary>
        public int MinimumPhotoThreshold { get; set; } = 3;

        /// <summary>
        /// 自动合并相似人物
        /// </summary>
        public bool AutoMergeSimilarPersons { get; set; } = false;

        /// <summary>
        /// 自定义排序规则
        /// </summary>
        [MaxLength(100)]
        public string CustomSortRule { get; set; }

        /// <summary>
        /// 显示名称格式
        /// </summary>
        [MaxLength(200)]
        public string DisplayNameFormat { get; set; }

        /// <summary>
        /// 自定义字段
        /// </summary>
        public Dictionary<string, object> CustomFields { get; set; } = new();
    }

    /// <summary>
    /// 隐私级别枚举
    /// </summary>
    public enum PrivacyLevel
    {
        /// <summary>
        /// 公开
        /// </summary>
        Public = 0,

        /// <summary>
        /// 正常
        /// </summary>
        Normal = 1,

        /// <summary>
        /// 私密
        /// </summary>
        Private = 2,

        /// <summary>
        /// 隐藏
        /// </summary>
        Hidden = 3
    }

    /// <summary>
    /// 人物关系实体
    /// </summary>
    public class PersonRelationship : FullAuditedEntity<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 源人物ID
        /// </summary>
        public virtual Guid SourcePersonId { get; protected set; }

        /// <summary>
        /// 目标人物ID
        /// </summary>
        public virtual Guid TargetPersonId { get; protected set; }

        /// <summary>
        /// 关系类型
        /// </summary>
        [Required]
        [MaxLength(100)]
        public virtual string RelationshipType { get; protected set; }

        /// <summary>
        /// 关系描述
        /// </summary>
        [MaxLength(500)]
        public virtual string Description { get; protected set; }

        /// <summary>
        /// 关系强度（0-1）
        /// </summary>
        public virtual double RelationshipStrength { get; protected set; }

        /// <summary>
        /// 关系开始时间
        /// </summary>
        public virtual DateTime? StartDate { get; protected set; }

        /// <summary>
        /// 关系结束时间
        /// </summary>
        public virtual DateTime? EndDate { get; protected set; }

        /// <summary>
        /// 是否为当前关系
        /// </summary>
        public virtual bool IsCurrent { get; protected set; }

        /// <summary>
        /// 关系标签
        /// </summary>
        public virtual List<string> Tags { get; protected set; }

        /// <summary>
        /// 源人物导航属性
        /// </summary>
        public virtual Person SourcePerson { get; protected set; }

        /// <summary>
        /// 目标人物导航属性
        /// </summary>
        public virtual Person TargetPerson { get; protected set; }

        protected PersonRelationship()
        {
            Tags = new List<string>();
        }

        public PersonRelationship(
            Guid id,
            Guid sourcePersonId,
            Guid targetPersonId,
            string relationshipType,
            double relationshipStrength = 0.5,
            Guid? tenantId = null) : base(id)
        {
            SourcePersonId = sourcePersonId;
            TargetPersonId = targetPersonId;
            RelationshipType = relationshipType;
            RelationshipStrength = Math.Max(0, Math.Min(1, relationshipStrength));
            IsCurrent = true;
            TenantId = tenantId;

            Tags = new List<string>();
        }

        /// <summary>
        /// 更新关系信息
        /// </summary>
        public virtual void UpdateRelationship(
            string relationshipType = null,
            string description = null,
            double? relationshipStrength = null,
            DateTime? startDate = null,
            DateTime? endDate = null)
        {
            if (relationshipType != null)
                RelationshipType = relationshipType;

            Description = description;

            if (relationshipStrength.HasValue)
                RelationshipStrength = Math.Max(0, Math.Min(1, relationshipStrength.Value));

            StartDate = startDate;
            EndDate = endDate;

            // 更新当前关系状态
            IsCurrent = !endDate.HasValue || endDate.Value > DateTime.Now;
        }

        /// <summary>
        /// 结束关系
        /// </summary>
        public virtual void EndRelationship(DateTime? endDate = null)
        {
            EndDate = endDate ?? DateTime.Now;
            IsCurrent = false;
        }

        /// <summary>
        /// 恢复关系
        /// </summary>
        public virtual void RestoreRelationship()
        {
            EndDate = null;
            IsCurrent = true;
        }

        /// <summary>
        /// 更新关系强度
        /// </summary>
        public virtual void UpdateStrength(double strength)
        {
            RelationshipStrength = Math.Max(0, Math.Min(1, strength));
        }

        /// <summary>
        /// 更新标签
        /// </summary>
        public virtual void UpdateTags(List<string> tags)
        {
            Tags = tags ?? new List<string>();
        }

        /// <summary>
        /// 添加标签
        /// </summary>
        public virtual void AddTag(string tag)
        {
            if (!string.IsNullOrWhiteSpace(tag) && !Tags.Contains(tag))
            {
                Tags.Add(tag);
            }
        }

        /// <summary>
        /// 移除标签
        /// </summary>
        public virtual void RemoveTag(string tag)
        {
            Tags.Remove(tag);
        }

        /// <summary>
        /// 检查是否为家庭关系
        /// </summary>
        public virtual bool IsFamilyRelationship()
        {
            return RelationshipType.Contains("家人") ||
                   RelationshipType.Contains("家庭") ||
                   RelationshipType.Contains("父母") ||
                   RelationshipType.Contains("子女") ||
                   RelationshipType.Contains("夫妻") ||
                   Tags.Contains("家庭");
        }

        /// <summary>
        /// 检查是否为友谊关系
        /// </summary>
        public virtual bool IsFriendshipRelationship()
        {
            return RelationshipType.Contains("朋友") ||
                   RelationshipType.Contains("友谊") ||
                   Tags.Contains("朋友");
        }
    }
}